﻿angular.module('app')
    .service('TaskSrv', ['$http', '$q',
        function ($http, $q) {
            var _tasks = [];
            var _comments = [];

            return {
                tasks: _tasks,
                comments: _comments,
                getTasksCount: function (user) {
                    return $http({ method: 'GET', url: 'api/tasks', params: { toid: '', user: user }, cache: false, headers: { 'Abortable': false } });
                },
                //api/tasks?user=cgrant&pageIndex=0&pageSize=5&searchFor=
                getTasksByUser: function (user, searchFor, pageSize, pageIndex) {
                    var deferred = $q.defer();

                    var start = new Date().getTime();

                    $http({ method: 'GET', url: 'api/tasks', params: { user: user, pageIndex: pageIndex, pageSize: pageSize, searchFor: searchFor }, cache: false })
                        .then(function (result) {
                            angular.copy(result.data, _tasks);
                            deferred.resolve();
                            },
                            function(error) {
                                deferred.reject();
                            });

                    //console.log('time taken for request (task): ' + (new Date().getTime() - start) + 'ms');
                    return deferred.promise;
                },
                //api/tasks/63889ce7-92a1-47f0-8ff8-1914197738ef
                getTaskByToid: function (taskOid) {
                    return $http({ method: 'GET', url: 'api/tasks/' + taskOid, cache: false });
                },
                //api/comments/7D3A5953-0055-463B-81F7-CEFA81809555
                getCommentsForTask: function (taskOid) {
                    return $http({ method: 'POST', url: 'api/comments/' + taskOid, cache: false });
                },
                taskOperation: function (toid, op, userName, result, message) {
                    return $http({ method: 'PATCH', url: 'api/tasks/' + toid + '/' + op, data: { 'acceptedBy': userName },params: {result: result, message: message}, cache: false });
                }
            };
        }
    ]);